<?php 

namespace controller;

require_once("View/LoginView.php");
require_once("Model/loginModel.php");

class loginController {

	/**
	 * @var loginView
	 */
	private $loginView;

	/**
	 * @var loginModel
	 */
	private $loginModel;

	/**
	 * @var String
	 */
	private $loginPass;
	/**
	 * @var String
	 */
	private $loginUser;

	/**
	 * @var string
	 */
	private $sessionUser;
	/**
	 * @var string
	 */
	private $sessionPass;

	/**
	 * initiate class member variables
	 */
	public function __construct() {
		$this->loginModel = new \model\loginModel();
		$this->loginView = new \view\loginView($this->loginModel);
		$this->loginPass = $this->loginView->loginPass();	
		$this->loginUser = $this->loginView->loginUser();
		$this->sessionUser = $this->loginModel->SessionUser();	
		$this->sessionPass = $this->loginModel->SessionPass();
	}

	/**
	 * Check if user is logging out else login
	 */
	public function doApp() {
		$username = $this->loginUser;
		if (!empty($this->loginPass)) {
			$password = md5($this->loginPass);	
		}
		else { $password = $this->loginPass; }		

		if($this->loginView->hasUserLoggedOut() && 
		   $this->checkSession()) {
			$this->doLogout();
		}
		else if ($this->checkSession() 
				 && $this->loginModel->validateSession()) {
			//do nothing, return empty form
		}
		else{ $this->doLogin($username, $password); }
		return $this->loginView->output();
	}

	/**
	 * set both view and model in logout state
	 * @return void
	 */
	public function doLogout() {
		$this->loginView->logout();
		$this->loginModel->logout();
	}

	/**
	 * @param  String $username
	 * @param  String $password
	 */
	public function doLogin($username, $password) {
		try {			
			if ($this->loginView->hasUserCookieLoggedIn() 
			&& $this->loginView->hasUserLoggedIn()) {	
				$this->loginModel->userLoggedIn = true;
				$this->loginView->createLoginCookie($username,$password);
				$this->loginModel->cookieIsSet = true;
				$this->loginModel->checkLogin($username, $password);	
				$this->loginView->goodLogin();
			}		
			else if ($this->checkSession()) {
				$this->loginModel->checkLogin($this->sessionUser, $this->sessionPass);
				$this->loginView->goodLogin();
			}	
			else if ($this->loginView->isCookieSet()) {
				$this->loginModel->cookieIsSet = true;
				$this->loginModel->userLoggedIn = false;
				$this->loginModel->checkLogin($username, $this->loginPass);
				$this->loginView->goodLogin();
			}		
			else if ($this->loginView->hasUserLoggedIn()) {
				$this->loginModel->checkLogin($username, $password);
				$this->loginView->goodLogin();
			}			
		} catch (\Exception $e) {$this->loginView->badLogin();}			
	}


	public function checkSession() {
		return $this->loginModel->checkSession();		
	}

}
